package com.celan.year2023.month11.day13;

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * obj.update(index,val);
 * int param_2 = obj.sumRange(left,right);
 */
class NumArray {

    int[] nums;
    int[] sums;

    public NumArray(int[] nums) {
        this.nums = nums;
        sums = new int[nums.length];
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            sums[i] = sum;
        }
    }

    public void update(int index, int val) {
        int old = nums[index];
        nums[index] = val;
        int diff = old - val;
        for (int i = index; i < sums.length; i++) {
            sums[i] -= diff;
        }
    }

    public int sumRange(int left, int right) {
        if (left == 0) return sums[right];
        return sums[right] - sums[left - 1];
    }

    public static void main(String[] args) {
        NumArray numArray = new NumArray(new int[]{1, 3, 5});
        int i = numArray.sumRange(0, 2);
        System.out.println(i);
        numArray.update(1, 2);
        int i2 = numArray.sumRange(0, 2);
        System.out.println(i2);
    }

}

